package com.loanbefore.watermark;
 
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Administrator on 2017-2-20.
 */

public class CompressionBitmap extends AsyncTask<String, Integer, Boolean> {
    private static final String TAG = CompressionBitmap.class.getSimpleName();
    private final ArrayList<HashMap<String, String>> arrayList;
    private final String cusName;
    private final String appId;
    private final String type;

    public CompressionBitmap(ArrayList<HashMap<String, String>> arrayList,
                             String cusName, String appId, String type) {
        this.arrayList = arrayList;
        this.cusName = cusName;
        this.appId = appId;
        this.type = type;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        for (int i = 0; i < arrayList.size(); i++) {
            if (("true").equals(arrayList.get(i).get("check"))) {
                String idPath = arrayList.get(i).get("id");
                String path = arrayList.get(i).get("path");
                String filePath = null;
                filePath = "/sdcard/smcs/Credit2015/" + cusName + "_" + appId
                        + "/" + type;
                // 将图片压缩保存
                try {
                    saveReducePic(path, filePath, idPath);
                } catch (Exception e) {
                   // LogUtil.e(TAG, e.getMessage());
                }
            }
        }
        return true;
    }

    /**
     * @see  //保存压缩后的图片
     * @param picPath
     *            原图路径
     * @param savePath
     *            压缩后的图片保存路径
     */
    public void saveReducePic(String picPath, String savePath, String id)
            throws Exception {
        // 创建文件
        File file = new File(savePath);
        if (!file.exists()) {
            file.mkdirs();
        }

        String[] a = picPath.split("/");

        Bitmap picbmp = loadBMP(picPath);
        try {
            FileOutputStream os = new FileOutputStream(savePath + "/" + id
                    + "_" + a[a.length - 1]);
            if (picbmp.compress(Bitmap.CompressFormat.JPEG, 50, os)) {
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (picbmp != null && !picbmp.isRecycled()) {
            picbmp.recycle();
            picbmp = null;
            System.gc();
        }
    }

    /**
     * @see //保存压缩后的图片
     * @param picPath
     *            原图路径
     * @param savePath
     *            压缩后的图片保存路径
     */
    public static void saveReducePic(String picPath, String savePath) {
        // 创建文件
        File file = new File(savePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String[] a = picPath.split("/");
        Bitmap picbmp = loadBMP(picPath);
        try {
            FileOutputStream os = new FileOutputStream(savePath + "/"
                    + a[a.length - 1]);
            if (picbmp.compress(Bitmap.CompressFormat.JPEG, 50, os)) {
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (picbmp != null && !picbmp.isRecycled()) {
            picbmp.recycle();
            picbmp = null;
            System.gc();
        }
    }

    /**
     * @see //保存压缩后的图片
     * @param picPath
     *            原图路径
     * @param savePath
     *            压缩后的图片保存路径
     * @param quality
     * 			      压缩比例1-100
     */
    public static void saveReducePic(String picPath, String savePath, int quality) {
        // 创建文件
        File file = new File(savePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String[] a = picPath.split("/");
        Bitmap picbmp = loadBMP(picPath);
        try {
            FileOutputStream os = new FileOutputStream(savePath + "/"
                    + a[a.length - 1]);
            if (picbmp.compress(Bitmap.CompressFormat.JPEG, quality, os)) {
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (picbmp != null && !picbmp.isRecycled()) {
            picbmp.recycle();
            picbmp = null;
            System.gc();
        }
    }

    /**
     * @see //文件decode成bitmap
     * @param path
     * @return
     */
    public static Bitmap loadBMP(String path){
        Bitmap bitmap = BitmapFactory.decodeByteArray(decodeBitmap(path), 0,
                decodeBitmap(path).length);
        return bitmap;
    }

    public static byte[] decodeBitmap(String path) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;// 设置成了true,不占用内存，只获取bitmap宽高
        BitmapFactory.decodeFile(path, opts);
        opts.inSampleSize = 2;
        opts.inJustDecodeBounds = false;// 这里一定要将其设置回false，因为之前我们将其设置成了true
        opts.inDither = false;
        opts.inTempStorage = new byte[16 * 1024];
        FileInputStream is = null;
        Bitmap bmp = null;
        ByteArrayOutputStream baos = null;
        try {
            is = new FileInputStream(path);
            bmp = BitmapFactory.decodeFileDescriptor(is.getFD(), null, opts);
            double scale = getScaling(opts.outWidth * opts.outHeight,
                    1024 * 600);
            Bitmap bmp2 = Bitmap.createScaledBitmap(bmp,
                    (int) (opts.outWidth * scale),
                    (int) (opts.outHeight * scale), true);
            bmp.recycle();
            baos = new ByteArrayOutputStream();
            bmp2.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            bmp2.recycle();
            return baos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.gc();
        }
        return baos.toByteArray();
    }

    private static double getScaling(int src, int des) {
        /**
         * 48 目标尺寸÷原尺寸 sqrt开方，得出宽高百分比 49
         */
        double scale = Math.sqrt((double) des / (double) src);
        return scale;
    }

}
